/**
 * Created by yong.liu on 2015/5/6.
 */
var app = angular.module("helloDir",[]);
app.run(function($templateCache){
  $templateCache.put("helloTemplateCached.html","<div>Hello everyone!</div>");
});
app.directive("hello",function(){
  return{
    restrict: "E",
    //template: "<div>Hello world!</div>",
    templateUrl: "helloTemplateCached.html",
    replace: true
  };
});

app.controller("dirCtrl",function($scope){
  $scope.title = "Click me to expand!";
  $scope.text = "Hi there folks，I am then content that was hidden but is now shown";
  $scope.expanders = [
    {title: "Click me to expand",text: "Hi ther folks,I am the content that was hidden bu is now shown."},
    {title: "Click this",text: "I am even better text than you have seen previously"},
    {title: "No, click me!",text: "I am text that should be seen before seeing other texts"}
  ];
});

app.directive("accordion",function(){
  return{
    restrict: 'EA',
    replace: true,
    transclude:true,
    template: '<div ng-transclude=""></div>',
    scope: {},
    controller: function(){
      var expanders = [];

      this.gotOpened = function(selectedExpander){
        angular.forEach(expanders,function(expander){
          if(selectedExpander != expander){
            expander.showMe = false;
          }
        });
      }

      this.addExpander = function(expander){
        expanders.push(expander);
      }

    }
  }
});

app.directive("expander", function () {
  return{
    restrict: 'EA',
    replace: true,
    transclude: true,
    require: "?^accordion",
    scope: {title:"=expanderTitle"},
    template: "<div><div class='title' ng-click='toggle()'>{{title}}</div>" +
              "<div class='body' ng-show='showMe' ng-transclude></div></div>",
    /*template: "<div><div class='title' >{{title}}</div>" +
    "<div class='body closed' ng-transclude></div></div>",*/
    link: function(scope,iElement,iAttrs,accordionController){
      scope.showMe = false;
      accordionController.addExpander(scope);

      scope.toggle = function(){
        scope.showMe = !scope.showMe;
      };
      /*var titleElement = angular.element(iElement.children().eq(0));
      var bodyElement = angular.element(iElement.children().eq(1));
      titleElement.bind("click",toggle);
      function toggle(){
        bodyElement.toggleClass("closed");
      }*/
    }
  }
});
